package com.tmall.controller;

import com.tmall.pojo.User;
import com.tmall.service.UserService;
import com.tmall.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;


/**
 * @author 吕兵星
 */
@CrossOrigin("*")
@RestController
@RequestMapping("/admin")
public class UserController {
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;



    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/selectOne/{id}")
    public Result selectOne(@PathVariable("id") Integer id) {
        return new Result(0,1,userService.queryById(id));
    }

    /**
     * TODO
     * @author 吕兵星
     * @date 2020/11/27 22:34
     * @param page
     * @param limit
     * @return com.tmall.util.Result
     */
    @GetMapping("/selectAll")
    public Result selectAll(@PathParam("page") int page,@PathParam("limit")  int limit){
        List<User> users = this.userService.queryAllByLimit((page - 1) * limit, limit);
        return new Result(0,userService.queryCount(),users);
    }
    @GetMapping("/selectUserCount")
    public int test(){
        return userService.queryCount();
    }
    /**
     * 通过实体作为筛选条件查询
     *
     * @param user 实例对象
     * @return 对象列表
     */
    @PostMapping("/getIfUsers")
    public Result queryAll(User user) {
        List<User> list = userService.queryAll(user);
        if (list !=null) {
            return new Result(0,list.size(), list);
        }else {
            return new Result(-1,0, null);
        }

    }


    @GetMapping("/deleteById")
    public Result deleteById(@PathParam("id")int id){
        boolean b = userService.deleteById(id);
        if (b) {
            return new Result(0,0,"success");
        }else {
            return new Result(-1,0,"failed");
        }
    }

    @PostMapping("/updateUser")
    public Result updateUser(User user){
        System.out.println(user.getId()+"||"+user.getName()+"||"+user.getPassword());
        try {
            User update = userService.update(user);
            return new Result(0,1,update);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(1,0,"failed");
        }

    }
}
